﻿import VTitle from '@/components/common/MainTitle.vue'
import EditContent from './EditContent.vue'
import GetSearch from './GetSearchInfo.vue'
import AddMutilData from './AddMutilData.vue'
// JSONEditor编辑器
import EditorMdJson from '@/components/EditorMd/EditorMdJson'
import axios from 'axios'
export default {
  data () {
    return {
      titleName: '元数据维护',
      categorys: [],
      checkedId: '',
      // 所有的元数据表
      tableList: [],
      defaultProps: {
        children: 'children',
        label: 'metadesc'
      },
      operationType: '',
      defaultExpanded: ['C000'],
      defaultChecked: [],
      filterText: '',
      // 右侧表格展示的信息
      table: {
        tableData: [],
        tableColumn: [],
        // 用于存储修改之前的数据
        ori_data: []
      },
      isEdit: false,
      searchKey: '',
      hadCreated: [],
      // 页码相关的数据
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      totalData: [],
      // 检索相关的
      mode: 'Normal',
      searchInfo: {
        filter_column: '',
        filter_op: '',
        filter_value: ''
      },
      loading: true,
      // 编辑字段的弹窗
      editInfo: {
        item: {
          text: ''
        }
      },
      showDialog: false,
      editRow: '',
      // 检索数据的弹窗
      showSearchData: false,
      // 设置wiki内容的部分
      settingWikiDialog: {
        dialogVisible: false,
        title: '',
        url: '',
        modal: false,
        opacity: 0
      },
      // iframe的高度
      iframeHeight: '800px',
      // 导入多条数据的弹窗
      showAddMutilDataDialog: false,
      // json弹窗
      showJsonDialog: false,
      jsonDialogValue: null,
      jsonDialogValueOut: null,
      jsonShowValue: false,
      jsonHeaderValue: null,
      jsonLoading: false
    }
  },
  computed: {
    getData () {
      const parentArray = []
      if (this.tableList.length) {
        this.categorys.forEach(parentVal => {
          const childrenArray = []
          this.tableList.forEach(sonVal => {
            if (parentVal.category_no === sonVal.category_no) {
              childrenArray.push(sonVal)
            }
          })
          const objTem = {
            treeId: parentVal.treeId,
            metaname: parentVal.metaname,
            metadesc: parentVal.metaname,
            category_name: parentVal.category_name,
            category_no: parentVal.category_no,
            hadOperation: false,
            disabled: true,
            children: childrenArray
          }
          parentArray.push(objTem)
        })
        return parentArray
      } else {
        return this.categorys
      }
    }
  },
  created () {
    // 页面开始加载时需要先加载iframe,通过修改modal和dialog的opacity的样式来给人没有展示的错觉
    this.settingWikiDialog.dialogVisible = true
    if (window.innerHeight < 768) {
      this.iframeHeight = '530px'
    }
    this.getTableData(1)
    this.getCategorys()
  },
  mounted () {
    // 获取iframe中的数据
    window.addEventListener('message', this.getIframeData)
  },
  methods: {
    // 获取所有的表的类型
    getCategorys () {
      this.$get('/metadata/category').then(data => {
        if (data.status === 200) {
          this.categorys = []
          if (data.data.result.length) {
            data.data.result.forEach(val => {
              const objTem = {
                treeId: val.category_no,
                metaname: val.category_name,
                metadesc: val.category_name,
                category_name: val.category_name,
                category_no: val.category_no,
                hadOperation: false,
                disabled: true
              }
              this.categorys.push(objTem)
            })
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取所有的表
    getTableData (isLoad) {
      // 页面开始加载时需要先加载iframe,通过修改modal和dialog的opacity的样式来给人没有展示的错觉
      if (isLoad) {
        setTimeout(() => {
          this.settingWikiDialog.dialogVisible = false
        }, 1000)
        setTimeout(() => {
          this.settingWikiDialog.modal = true
          this.settingWikiDialog.opacity = 1
          this.settingWikiDialog.url = $URL.KB_SHOW_URL + '/#/docWiki?_token=' + sessionStorage.getItem('token')
        }, 2000)
      }
      this.$get('/metadata').then(data => {
        if (data.status === 200) {
          this.tableList = []
          this.hadCreated = []
          if (data.data.result.length) {
            this.tableList = data.data.result
            this.tableList.forEach(val => {
              val.hadOperation = true
              val.treeId = val.metauid
              if (val.is_created) {
                this.hadCreated.push(val)
              }
            })
            if (this.hadCreated.length) {
              this.showTableInfo(this.hadCreated[0])
            } else {
              this.loading = false
            }
          } else {
            this.loading = false
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击树状结构的表时
    handleNodeClick (data, node, self) {
      if (data.hadOperation && data.is_created) {
        // 当点击的不是已经选中的选框时
        if (this.checkedId !== data) {
          this.checkedId = data
          this.$refs.myTree.setCheckedNodes([data])
          this.showTableInfo(data)
        }
      } else if (data.hadOperation && !data.is_created) {
        this.$message({
          message: '该元素表还没有创建，无法查看,可以在元数据表结构管理界面进行创建',
          type: 'warning'
        })
      }
    },
    // 展示表的内容
    showTableInfo (data) {
      this.operationType = ''
      this.checkedId = data
      this.defaultChecked = [data.metauid]
      this.defaultExpanded = [data.category_no]
      // 需要将表格中的数据还原
      this.pageSize = 10
      this.currentPage = 1
      this.searchInfo = {
        filter_column: '',
        filter_op: '',
        filter_value: ''
      }
      this.mode = 'Normal'
      this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
    },
    // 获取选中表的信息
    getCheckedInfo (limit, page, searchInfo, mode) {
      this.operationType = ''
      this.searchKey = ''
      this.loading = true
      let params = {}
      if (mode !== 'Normal') {
        params = {
          mode: mode,
          filter_column: searchInfo.filter_column,
          filter_op: searchInfo.filter_op,
          filter_value: searchInfo.filter_value
        }
      } else {
        params = {
          mode: mode,
          limit: limit,
          page: page,
          filter_column: searchInfo.filter_column,
          filter_op: searchInfo.filter_op,
          filter_value: searchInfo.filter_value
        }
      }
      this.$get('/metadataset/' + this.checkedId.metauid, params).then(data => {
        let dataInfo = data.data.result
        this.loading = false
        if (dataInfo.code === 'success') {
          if (dataInfo.columns.length) {
            // 自定义表格的表头
            this.table.tableColumn = []
            dataInfo.columns.forEach((val, index) => {
              let objExam = {
                indexName: val.column_name,
                is_allow_empty: val.is_allow_empty,
                ui_type: val.ui_type,
                is_pk: val.is_pk,
                ext_parameters: val.ext_parameters
              }
              if (val.column_desc !== '') {
                objExam.text = val.column_desc
              } else {
                objExam.text = val.column_name
              }
              this.table.tableColumn.push(objExam)
            })
            // 该表的数据存储在table.tableData
            this.totalData = JSON.parse(JSON.stringify(dataInfo.data))
            this.table.tableData = this.totalData
            // 该表数据的初始值
            this.table.ori_data = JSON.parse(JSON.stringify(dataInfo.data))
            // 页码相关的信息
            if (mode === 'Normal') {
              this.totalLength = dataInfo.total_count
              this.pageSize = dataInfo.limit
              this.currentPage = dataInfo.page
            }
          }
        } else if (dataInfo.code === 'failed' && dataInfo.msg === '元数据表不存在') {
          this.$message({
            message: '该元素表还没有创建,请先在元数据结构维护中创建该表',
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 表头的Pk显示
    handelHelp (h, {column}) {
      return (
        h('span', [column.label])
      )
    },
    handelHelpKey (h, {column}) {
      return (
        h('span', [
          h('span', {style: {color: 'red'}}, ['*']),
          h('span', [column.label])
        ])
      )
    },
    // 点击表格的某一单元格时
    editTableCloumn (item, row, index) {
      this.showDialog = true
      this.editInfo.item = item
      this.editInfo.row = row
      this.editInfo.status = 'edit'
      // 选中表的uid
      this.editInfo.funUid = this.checkedId.metauid
      this.editRow = index
    },
    sureEdit (editContent) {
      this.showDialog = false
      this.table.tableData[this.editRow][this.editInfo.item.indexName] = editContent
    },
    showTableCloumn (item, row, index) {
      this.showDialog = true
      this.editInfo.item = item
      this.editInfo.row = row
      this.editInfo.status = 'show'
      // 选中表的uid
      this.editInfo.funUid = this.checkedId.metauid
      this.editRow = index
    },
    addTableCloumn (item, row, index) {
      this.showDialog = true
      this.editInfo.item = item
      this.editInfo.row = row
      this.editInfo.status = 'add'
      // 选中表的uid
      this.editInfo.funUid = this.checkedId.metauid
      this.editRow = index
    },
    // ui_type为wiki类型时,点击设置内容
    setWikiContent (item, row, index) {
      let isDisabled = false
      if (this.operationType !== 'edit' && row.newData !== 'newData') {
        // 只读状态
        isDisabled = true
      }
      if (isDisabled && !row[item.indexName]) {
        this.$message({
          message: '该字段暂未生成文档...',
          type: 'warning',
          duration: 3000
        })
        return
      }
      if (!item.ext_parameters) {
        this.$message({
          message: '该字段暂未选择文档模板,无法进行其它操作',
          type: 'warning',
          duration: 3000
        })
        return
      }
      this.editRow = index
      this.editInfo.item = item
      this.editInfo.row = row
      this.settingWikiDialog.dialogVisible = true
      this.settingWikiDialog.title = isDisabled ? '查看(' + item.text + ')的内容' : '设置(' + item.text + ')的内容'
      this.settingWikiDialog.url = $URL.KB_SHOW_URL + '/#/docWiki?_token=' + sessionStorage.getItem('token')
      let settingToIframe = {
        isDisabled: isDisabled,
        templateId: item.ext_parameters, // 模板的id
        docId: row[item.indexName], // 文档的id--如果已经生成了文档
        webOrigin: $URL.SYSTEM_SHOW_URL // 系统的地址,iframe判断使用
      }
      // 将数据传递到iframe中
      this.$refs.myWikiIframe.contentWindow.postMessage(settingToIframe, '*')
    },
    // 获取iframe中的数据
    getIframeData (e) {
      if (e.data && e.origin === $URL.KB_SHOW_URL) {
        if (e.data.closed === 'fail') {
          this.$set(this.settingWikiDialog, 'dialogVisible', false)
        } else if (e.data.closed === 'success') {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.$set(this.table.tableData[this.editRow], this.editInfo.item.indexName, e.data.editContent)
          this.$set(this.settingWikiDialog, 'dialogVisible', false)
        }
      }   
    },
    // el-tree只能单选
    handleCheckChange (data, node, self) {
      // 点击未选中的复选框
      if (data.is_created) {
        if (node) {
          this.checkedId = data
          this.$refs.myTree.setCheckedNodes([data])
        } else {
          // 点击已选中的复选框
          this.$refs.myTree.setCheckedNodes([this.checkedId])
        }
      } else {
        this.$refs.myTree.setCheckedNodes([])
      }
    },
    filterNode (value, data) {
      if (!value) return true
      return data.metadesc.indexOf(value) !== -1 || data.metaname.indexOf(value) !== -1
    },
    // 向表中新增一条数据
    addData () {
      this.operationType = 'add'
      if (this.table.tableColumn.length) {
        let objExam = {}
        this.table.tableColumn.forEach(val => {
          let index = val.indexName
          objExam[index] = ''
        })
        objExam.newData = 'newData'
        this.table.tableData.unshift(objExam)
      }
    },
    // 提交新增的方法
    submitAdd () {
      if (this.table.tableData.length) {
        let newArry = []
        this.table.tableData.forEach(val => {
          // 在表格中所有的数据中，找到新增的数据
          if (val.newData === 'newData') {
            // 将新增数据中的 newData 属性和值去掉并保存到新的数组中
            let objExam = {}
            for (let key in val) {
              if (key !== 'newData') {
                objExam[key] = val[key]
              }
            }
            newArry.push(objExam)
          }
        })
        if (newArry.length) {
          this.$post('/metadataset', {
            id: this.checkedId.metauid,
            data: newArry
          }).then(data => {
            if (data.data.result.code === 'success') {
              this.$message({
                message: '添加数据成功！',
                type: 'success'
              })
              this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
            } else if (data.data.result.code === 'failed') {
              this.$message({
                message: data.data.result.msg,
                type: 'error'
              })
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          this.$message({
            message: '该元素表中还没有新增的数据数据，不需要提交',
            type: 'warning'
          })
        }
      } else {
        this.$message({
          message: '该元素表中还没有新增的数据数据，不需要提交',
          type: 'warning'
        })
      }
    },
    // 编辑数据的方法
    handleEdit () {
      if (this.table.tableData.length) {
        this.operationType = 'edit'
      } else {
        this.$message({
          message: '该元素表中还没有数据，无法进行编辑操作',
          type: 'warning'
        })
      }
    },
    // 提交编辑的方法
    submitEdit () {
      let changeInfo = this.justifyChangeData()
      this.$patch('/metadataset/' + this.checkedId.metauid, {
        ori_data: changeInfo.oriData,
        data: changeInfo.changedData
      }).then(data => {
        if (data.data.result.code === 'success') {
          this.$message({
            message: '编辑数据成功',
            type: 'success'
          })
          this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
        } else if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 判断编辑的数据
    justifyChangeData () {
      let changeInfo = {
        oriData: [],
        changedData: []
      }
      this.totalData.forEach((val, index) => {
        let hadChanged = false
        this.table.tableColumn.forEach(columnVal => {
          if (val[columnVal.indexName] !== this.table.ori_data[index][columnVal.indexName]) {
            hadChanged = true
          }
        })
        if (hadChanged) {
          changeInfo.oriData.push(this.table.ori_data[index])
          changeInfo.changedData.push(val)
        }
      })
      return changeInfo
    },
    // 删除单条数据时
    handleSingleDelete (row, index) {
      // 当为新增时移除新增项时
      if (this.operationType === 'add') {
        this.table.tableData.splice(index, 1)
      } else {
        this.submitDelete(this.checkedId.metauid, [row])
      }
    },
    // 删除该表下所有的数据时
    handleDeleteTable (tableData) {
      this.$confirm('此操作将永久删除该表下所有数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/metadataset/' + tableData.metauid + '/all').then(data => {
          if (data.status === 204) {
            this.$message({
              message: '数据删除成功',
              type: 'success'
            })
            this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 提交删除的方法
    submitDelete (uid, fromDelete) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/metadataset/' + uid, {
          data: {
            data: fromDelete
          }
        }).then(data => {
          if (data.status === 204) {
            this.$message({
              message: '数据删除成功',
              type: 'success'
            })
            this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 点击取消按钮时
    resetForm () {
      this.operationType = ''
      this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
    },
    // 点击确定提交的按钮时
    submitForm (submitType) {
      if (submitType === 'edit') {
        this.submitEdit()
      } else if (submitType === 'add') {
        this.submitAdd()
      }
    },
    // 检索数据的弹窗
    searchData () {
      this.showSearchData = true
    },
    sureSearch (fromSearch) {
      this.showSearchData = false
      this.mode = fromSearch.mode
      this.searchInfo.filter_column = fromSearch.filter_column
      this.searchInfo.filter_op = fromSearch.filter_op
      this.searchInfo.filter_value = fromSearch.filter_value
      this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
    },
    // 新增多条数据时
    addMutilData () {
      this.showAddMutilDataDialog = true
    },
    // 操作成功时
    operationSuccess () {
      this.showAddMutilDataDialog = false
      this.getCheckedInfo(this.pageSize, this.currentPage, this.searchInfo, this.mode)
    },
    // json的弹窗
    getTableJson () {
      this.showJsonDialog = true
      this.jsonDialogValue = null
      this.jsonDialogValue = null
      this.jsonDialogValueOut = null
      this.jsonLoading = false
    },
    // 关闭弹窗
    closeJsonDialog () {
      this.showJsonDialog = false
      this.jsonDialogValue = null
      this.jsonDialogValueOut = null
      this.jsonHeaderValue = null
      this.jsonLoading = false
    },
    // 提交时
    handleJsonSubmit () {
      this.$refs.myJSONEditor.getMdValue()
      if (!this.jsonHeaderValue) {
        this.$message({
          message: '请输入请求头的值',
          type: 'warning'
        })
        return
      }
      if (!this.jsonDialogValue) {
        this.$message({
          message: '请输入参数',
          type: 'warning'
        })
      } else {
        if (this.jsonDialogValue !== 'JsonError') {
          this.jsonLoading = true
          axios({
            url: $URL.CENTER_API + '/metadataset/excute/express',
            method: 'post',
            data: JSON.parse(decodeURIComponent(this.jsonDialogValue)),
            headers: {
              'SystemSecretKey': this.jsonHeaderValue
            }
          }).then(data => {
            try {
              this.jsonShowValue = !this.jsonShowValue
              this.jsonLoading = false
              this.jsonDialogValueOut = encodeURIComponent(JSON.stringify(data.data))
            }
            catch (error) {
              this.$message({
                message: '返回数据有误',
                type: 'warning'
              })
            }
          }).catch(error => {
            this.jsonLoading = false
            console.log(error)
          })
        }
      }
    }
  },
  destroyed() {
    window.removeEventListener('message', this.getIframeData)
  },
  watch: {
    // 搜索的功能
    searchKey: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.table.tableData = this.totalData
        } else {
          this.table.tableData = []
          // 所有的数据进行循环
          this.totalData.forEach((value, index) => {
            let hadEqualKey = false
            // 所有的字段进行循环
            this.table.tableColumn.forEach(val => {
              let equalKey = val.indexName
              // 进行检索匹配
              if (value[equalKey].toString().indexOf(this.searchKey) !== -1) {
                hadEqualKey = true
              }
            })
            // 当有匹配的字段时，将该字段加到 filterData中
            if (hadEqualKey) {
              this.table.tableData.push(value)
            }
          })
        }
      },
      deep: true
    },
    filterText (val) {
      this.$refs.myTree.filter(val)
    }
  },
  components: {
    VTitle,
    EditContent,
    GetSearch,
    AddMutilData,
    EditorMdJson
  }
}
